package com.xy.sql.xml.fragment;

import com.xy.sql.xml.core.XySQLExePara;
import com.xy.sql.xml.core.XySQLKit;
import com.xy.sql.xml.core.XySQLTaskContext;
import com.xy.sql.xml.itf.XySQLRegister;
import com.xy.sql.xml.kit.XySQLScriptKit;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XySQLFieldFragment implements IXySQLFragment {
    private static final String FIELD_ATT_JDBCTYPE = "jdbctype";

    private static final String FIELD_FUNC_NAME = "function";

    private String oriSql;

    private String fieldName;

    private boolean direct;

    private String funcName;

    private Map<String, String> propertyMap = new HashMap<>();

    public XySQLFieldFragment(String inSql, boolean direct) throws Exception {
        this.oriSql = inSql;
        this.direct = direct;
        String tempSql = oriSql.trim();
        String fieldStr = tempSql.substring(2, tempSql.length() - 1);
        fieldStr = fieldStr.trim();
        int splitIndex = fieldStr.indexOf(",");
        //无其它信息，最主要场景
        if (splitIndex < 0) {
            fieldName = fieldStr;
            return;
        }
        if (splitIndex == 0) {
            throw new Exception("表达式( " + tempSql + " )定义错误!");
        }
        fieldName = fieldStr.substring(0, splitIndex);
        //取得属性列表
        propertyMap.putAll(XySQLScriptKit.prop(fieldName, fieldStr, ","));
        funcName = propertyMap.get(FIELD_FUNC_NAME);
        if (funcName != null && funcName.trim().length() == 0) {
            funcName = null;
        }
    }

    /**
     * 取得值
     *
     * @param key
     * @return
     */
    private Object getValue(String key,XySQLTaskContext task) {
        String type = propertyMap.get(FIELD_ATT_JDBCTYPE);
        return XySQLKit.getValue(key,type, task);
    }

    @Override
    public List<XySQLExePara> boundSql(XySQLTaskContext task) {
        //取得值
        Object newValue = getValue(fieldName,task);
        if (funcName != null) {
            newValue = XySQLRegister.getFunction().action(newValue, funcName, propertyMap);
        }
        if (newValue == null) {
            return Arrays.asList(new XySQLExePara("?", null, true));
        }
        if (direct) {
            return Arrays.asList(new XySQLExePara(newValue.toString(), null));
        }
        return Arrays.asList(new XySQLExePara(" ? ", newValue, true));

    }

}
